//
//  DevSettingTypeModel.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/30.
//

#import "DevSettingTypeModel.h"
#import "DevSettingModel.h"
#import "SYChartTool.h"
#import "RHDeviceModel.h"

@implementation DevSettingTypeModel

//groupIdx 南非微网mppt模块组下标,其他的模块可随便传
+(DevSettingTypeModel *)getDataArray:(DevSettingType)type mpptGroupIndex:(NSInteger)groupIdx deviceModel:(RHDeviceModel *)devModel{
    NSArray *file_names = @[@"setting_master",
                            @"setting_inverter",
                            @"setting_pcs",
                            @"setting_dcdcin",
                            @"setting_dcdcout",
                            @"setting_ems",
                            @"setting_conditioner",
                            @"setting_conditioner"];
    
    
    if(devModel.inverterType == DevInverterTypeRYY6K||
       devModel.inverterType == DevInverterTypeRYY12K){
        NSString *fileName = @"";
        if(devModel.inverterType == DevInverterTypeRYY6K){//日月元
            fileName = @"setting_ao_ryy_pcs";
        }
        
        if(devModel.inverterType == DevInverterTypeRYY12K){//日月元2
            //Inv1_BatMaxChCurr       max  120
            //Inv1_MaxFePower         max  6000
            fileName = @"setting_ao_ryy2_pcs";
        }
        
        if(devModel.inverterType == DevInverterTypeNT){//纳通
            fileName = @"setting_ao_nt_pcs";
        }
        
        file_names = @[@"setting_master",
                       fileName,
                       @"",
                       @"",
                       @"",
                       @"setting_ao_ems",
                       @"",
                       @""];
    }
    
    
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:file_names[type]];
    NSLog(@"--->加载的json文件:%@",file_names[type]);
    
    
    
    DevSettingModel *model = [DevSettingModel yy_modelWithDictionary:dict];
    DevSettingTypeModel *type_model = [[DevSettingTypeModel alloc] init];
    type_model.settingType = type;
    type_model.dataList = [model.dataList mutableCopy];
    
    //日月元的Iverter要将原来拆分成四组
    
    //日月元
    if(devModel.inverterType == DevInverterTypeRYY6K||
       devModel.inverterType == DevInverterTypeRYY12K){
        NSArray *groupTitle = @[@"Time Calibration",@"System Setting",@"Grid Type Setting",@"Advanced Setting",@"Work Mode Setting"];
        NSArray *workModeJsonFiles = @[@"setting_ao_ryy_pcs_NoMode",
                                       @"setting_ao_ryy_pcs_SelfUseMode",
                                       @"setting_ao_ryy_pcs_BackupMode",
                                       @"setting_ao_ryy_pcs_LowCostACChargeModel",
                                       @"setting_ao_ryy_pcs_OffGridMode",
                                       @"setting_ao_ryy_pcs_SelfDefineMode"
        ];
        NSArray *groupKeys = @[@[@"SystemTimeAligned"],
                               @[
                                   @"Inv1_BatType",
                                   @"Inv1_ParallOutEn",
                                   @"Inv1_PvParallelEn",
                                   @"Inv1_ExtemalCTEn",
                                   @"Inv1_GenePortEn",
                                   @"Inv1_LcdSleepT",
                                   @"Inv1_BuzzerEn"],
                               @[@"Inv1_OutRatedVA",
                                 @"Inv1_ACOutF",
                                 @"Inv1_AngleL1L2"],
                               @[@"Inv1_BatMaxChCurr",
                                 @"Inv1_MaxDisGridCurr",
                                 @"Inv1_MaxFePower",
                                 @"Inv1_ChAcitBat",
                                 @"Inv1_GeneAcInEn",
                                 @"Inv1_WideAcinRan",
                                 @"Inv1_ACOutConEn"],
                               @[]
        ];
        
        NSMutableArray *dataListArr = [NSMutableArray array];
        
        //把第二组拆分成三组
        [groupKeys enumerateObjectsUsingBlock:^(NSArray  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            DevSettingModel *model = [type_model.dataList lastObject];
            DevSettingModel *tempModel = [[DevSettingModel alloc]init];
            tempModel.nickname = groupTitle[idx];
            tempModel.field = model.field;
            tempModel.type = model.type;
            tempModel.keys = groupKeys[idx];
            NSMutableArray *temp_propertyList = [NSMutableArray array];
            NSArray *keyArr = groupKeys [idx];
            [keyArr enumerateObjectsUsingBlock:^(NSString  *_Nonnull fieldName, NSUInteger idx, BOOL * _Nonnull stop) {
                [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull settingModel, NSUInteger index, BOOL * _Nonnull stop) {
                    if([settingModel.field isEqualToString:fieldName]){
                        [temp_propertyList addObject:settingModel];
                    }
                }];
            }];
            //最后一组
            if(idx == 4){
                //工作模式
                //根据工作模式加载对应的json文件
                NSInteger work_mode = [devModel.dataInfo[@"Inv1_WorkModeSet"] integerValue];
                
                NSString *path = [[NSBundle mainBundle] pathForResource:workModeJsonFiles[work_mode] ofType:@"json"];
                NSLog(@"---->加载的文件名:%@",workModeJsonFiles[work_mode]);
                NSData *data = [[NSData alloc] initWithContentsOfFile:path];
                
                NSArray *dataArr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                
                tempModel.properList = [NSArray yy_modelArrayWithClass:[DevSettingModel class] json:dataArr];
                [dataListArr addObject:tempModel];
                
            }else{
                tempModel.properList = temp_propertyList.copy;
                [dataListArr addObject:tempModel];
            }
            
            //如果是(Self Defined Mode)模式,  这里要根据 P_MachineModel 来确定是否有(Charger source priority)这一项
            if([devModel.dataInfo[@"Inv1_WorkModeSet"] integerValue] == 5){
                __block NSInteger machineModel = [devModel.dataInfo[@"Inv1_MachineModel"] integerValue];
                __block NSInteger machineIndex = -1;
                [tempModel.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if([obj.field isEqualToString:@"Inv1_MachineModel"]){
                        [obj.selectList enumerateObjectsUsingBlock:^(DevSettingOptionModel * _Nonnull optModel, NSUInteger idx, BOOL * _Nonnull stop) {
                            if(optModel.textValue == machineModel){
                                machineIndex = idx;
                            }
                        }];
                    }
                    
                }];
                if(machineIndex >=0){
                    [tempModel changeRYYMachineModel:machineIndex];
                }
                
            }
            
        }];
        type_model.dataList = dataListArr.copy;
    }
    
    //纳通
    if(devModel.inverterType == DevInverterTypeNT){
        NSArray *groupTitle = @[@"Time Calibration",@"System Setting",@"Com Addr Setting",@"Advanced Setting",@"Password Setting",@"Command"];
        
        NSArray *groupKeys = @[@[@"SystemTimeAligned"],
                               @[
                                   @"P_SysOnOff",
                                   @"P_Language",
                                   @"P_WorkMode"],
                               @[@"P_ModbusAddr",
                                 @"P_Meter1Addr",
                                 @"P_Meter2Addr",
                                 @"P_Meter3Addr"],
                               @[@"P_GridCode",
                                 @"P_BatModelSet",
                                 @"P_MinSoC",
                                 @"P_MinFeeSoC",
                                 @"P_RemoteCtlSet",
                                 @"P_Drm0Set",
                                 @"P_RCREn",
                                 @"P_Meter1En",
                                 @"P_Meter2En",
                                 @"P_Meter3En",
                                 @"P_BypRelayEn",
                                 @"P_ParallModeSet"],
                               @[@"P_PassWord"],
                               @[@"P_ClearStat",
                                 @"P_ResFacSet",
                                 @"P_ClearEvent",
                                 @"P_ClearHFault"]
        ];
        
        NSMutableArray *dataListArr = [NSMutableArray array];
        //先把指令加进来
        [dataListArr addObject:[type_model.dataList firstObject]];
        //分组
        [groupKeys enumerateObjectsUsingBlock:^(NSArray  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            DevSettingModel *model = [type_model.dataList lastObject];
            DevSettingModel *tempModel = [[DevSettingModel alloc]init];
            tempModel.nickname = groupTitle[idx];
            tempModel.field = model.field;
            tempModel.type = model.type;
            tempModel.keys = groupKeys[idx];
            NSMutableArray *temp_propertyList = [NSMutableArray array];
            NSArray *keyArr = groupKeys [idx];
            [keyArr enumerateObjectsUsingBlock:^(NSString  *_Nonnull fieldName, NSUInteger idx, BOOL * _Nonnull stop) {
                [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull settingModel, NSUInteger index, BOOL * _Nonnull stop) {
                    if([settingModel.field isEqualToString:fieldName]){
                        [temp_propertyList addObject:settingModel];
                    }
                }];
            }];
            
            tempModel.properList = temp_propertyList.copy;
            [dataListArr addObject:tempModel];
            
        }];
        type_model.dataList = dataListArr.copy;
    }
    
    //只留第一个时间校准和最后一个工作模式
    type_model.dataList = @[[type_model.dataList firstObject],[type_model.dataList lastObject]];
    
    
    return type_model;
}




- (void)setMDataList{
    
    NSArray *m_names = @[@"M_R2",
                         @"M_PTcellov",
                         @"M_PTcellvu",
                         @"M_PTcellvd",
                         @"M_PTtvo",
                         @"M_PTtvu",
                         @"M_PTtempco",
                         @"M_PTtempcu",
                         @"M_PTtempdo",
                         @"M_PTtempdu",
                         @"M_PTtempeo",
                         @"M_PTtempeu",
                         @"M_PTtempmo",
                         @"M_PTsocu",
                         @"M_PTcurco",
                         @"M_PTcurdo",
                         @"M_PTtempbo",
                         @"M_PTresu",
                         @"M_PTsocuir",
                         @"M_PTsoct",
                         @"M_PTsocui"];
    self.mDataList = m_names;
    
}

- (void)readDefult:(NSDictionary *)dic {
    //日月元 工作模式除了 (self defined mode)读取默认值,其他模式不读取
    BOOL isRYYDev =  [dic[@"Inv_DevType"] integerValue] == 1 || [dic[@"Inv_DevType"] integerValue] == 2;
    
    //纳通
    BOOL isNTDev =  [dic[@"Inv_DevType"] integerValue] == 100;
    
    for (DevSettingModel *model in self.dataList) {
        
        NSDictionary *superDic = dic;
        
        if (superDic&&model.properList.count>0) {
            //是不是工作模式组
            BOOL isWorkModeSection = NO;
            for (DevSettingModel *child_model in model.properList) {
                if([child_model.field isEqualToString:@"Inv1_WorkModeSet"]){
                    isWorkModeSection = YES;
                    break;
                }
            }
            //是否是self define mode
            NSInteger workModeSet = [dic[@"Inv1_WorkModeSet"] integerValue];
            NSLog(@"---->读到的工作模式:%ld",workModeSet);
            BOOL isSelfDefMode = (workModeSet == 5);
            //先处理一下结构
            if(isRYYDev && isWorkModeSection){
                if(isSelfDefMode){
                    //先根据machine model 加载对应json
                    [model handleRYYWorkModeWithDevInfo:superDic];
                    //加载部分数据
                    [model loadRYYWorkModeDataWithDevInfo:superDic];
                    
                }else{
                    //其他模式只加载json文件,不读取数据
                    if(workModeSet > 0){
                        [model changeRYYWorkMode:workModeSet - 1];
                        //                        continue;
                    }
                }
            }
            
            
            for (DevSettingModel *child_model in model.properList) {
                NSLog(@"---->字段名:%@ 是否禁用：%d",child_model.field,child_model.disable);
                //如果是禁用的字段，就不加载，取json文件里的值
                if(child_model.disable){
                    if(([child_model.field isEqualToString:@"Inv1_BatChEn"]||[child_model.field isEqualToString:@"Inv1_ACBatChEn"]) && isSelfDefMode){
                        //这两个值如果是在自定义模式下,要读取实际值,上面已经对根据这两个值来显示Charger source priority的选项做了处理
                    }else{
                        continue;
                    }
                    
                }
                if([child_model.field isEqualToString:@"Inv1_chgPri"]){
                    continue;
                }
                if(isSelfDefMode && [child_model.field isEqualToString:@"Inv1_MachineModel"]){
                    if(([dic[@"Inv1_MachineModel"] integerValue] == 77) && ([dic[@"Inv1_PVEnerSuPri"] integerValue] == 3)){
                        //P_MachineModel = 77 并且 P_PVEnerSuPri = 3的时候, 要将 77(Grid-Tied With Backup) 改成显示 78(Time of Use) ,所以这里也不赋值
                        NSLog(@"------>不赋值");
                        continue;
                    }
                    
                    //读取时对  Off-Gird Ⅱ 的处理  ,如果 P_PVEnerSuPri 是0 (也就是 Battery-Load-Grid ),那么将P_PVEnerSuPri的值改为 152
                    //所以不赋值
                    if(([dic[@"Inv1_MachineModel"] integerValue] == 150) && ([dic[@"Inv1_PVEnerSuPri"] integerValue] == 0)){
                        NSLog(@"------>不赋值2");
                        continue;
                    }
                }
                
                
                if ([superDic[child_model.field] isKindOfClass:[NSString class]]) {
                    child_model.content = superDic[child_model.field];
                }else{
                    NSNumber *number = superDic[child_model.field];
                    if (child_model.ratio) {
                        number = @([superDic[child_model.field] integerValue]*[child_model.ratio doubleValue]);
                    }
                    //开关类型,值超过1的情况
                    if([child_model.type isEqualToString:@"switch"]&& [number integerValue]>1){
                        number = (0);
                    }
                    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
                    formatter.numberStyle = NSNumberFormatterDecimalStyle;
                    //formatter.maximumFractionDigits = 1;
                    [formatter setRoundingMode: NSNumberFormatterRoundDown];
                    
                    child_model.content = [[formatter stringFromNumber:number] stringByReplacingOccurrencesOfString:@"," withString:@""];
                    
                    
                }
                
                
                if([child_model.type isEqualToString:@"select"]){
                    child_model.inputModel.content = child_model.content;
                    for (DevSettingOptionModel *select_model in child_model.inputModel.optionList) {
                        if([child_model.content integerValue] == select_model.textValue){
                            child_model.inputModel.content = select_model.text;
                            child_model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
                        }
                    }
                }
                
                if([child_model.type isEqualToString:@"date"] && (isRYYDev||isNTDev)){
                    //日月元或者纳通 Inverter 时间校准
                    child_model.content = [NSString stringWithFormat:@"20%02ld/%02ld/%02ld %02ld:%02ld:%02ld",[superDic[@"Inv1_RTCYear"] integerValue],[superDic[@"Inv1_RTCMonth"] integerValue],[superDic[@"Inv1_RTCDay"] integerValue],[superDic[@"Inv1_RTCHour"] integerValue],[superDic[@"Inv1_RTCMinute"] integerValue],[superDic[@"Inv1_RTCSecond"] integerValue]];
                }
                
                
            }
        }else{
            //没有值
            if ([dic[model.field] isKindOfClass:[NSString class]]) {
                model.content = dic[model.field];
            }else{
                NSNumber *number = dic[model.field];
                NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
                formatter.numberStyle = NSNumberFormatterDecimalStyle;
                //formatter.maximumFractionDigits = 1;
                model.content = [[formatter stringFromNumber:number] stringByReplacingOccurrencesOfString:@"," withString:@""];
            }
        }
    }
    
    NSLog(@"------");
}










@end
